package servlet;

import entity.Product;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("*.product")
public class ProductServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        switch (path) {
            case "/findAll.product":
                findAll(request, response);
                break;
            case "/findById.product":
                findById(request, response);
                break;
        }
    }

    protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Product> products = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                products.add(product);
            }
            request.setAttribute("products", products);
//            request.getRequestDispatcher("/list.jsp").forward(request, response);
            request.getRequestDispatcher("/jquery/list.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Product product = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
            }
            // 此时,后台需要的商品对象数据已经查询出来
            // 如何将该数据以字符串的格式传递到前台?JSON
            // String productJson = "{'id':" + product.getId() + ",'name':'" + product.getName() + "','price':" + product.getPrice() + "}";

            // 可以使用JSON工具自动拼接JSON字符串
            // 将指定的Java对象product转换成JSON对象jsonObject
            JSONObject jsonObject = JSONObject.fromObject(product);
            // 将JSON对象转换成JSON格式的字符串
            String productJson = jsonObject.toString();

            List<Product> list = new ArrayList<>();
            // 将指定对象集合转换成JSON对象数组
//            JSONArray jsonArray = JSONArray.fromObject(list);
//            jsonArray.toString();

            PrintWriter out = response.getWriter();
            out.println(productJson);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
